﻿using System;
using System.ComponentModel;
using System.Drawing.Design;
using System.Windows.Forms;
using Argos.Windows.Forms;

namespace Argos.Design
{
	/// <summary>
	/// A generic type editor that displays a property grid dialog
	/// to be used to edit values with.
	/// </summary>
	/// <typeparam name="TValue">The type of value to edit with this type editor.</typeparam>
	public class GenericTypeEditor<TValue> : UITypeEditor
	{

		public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
		{
			using (PropertyEditorDialog dlg = new PropertyEditorDialog())
			{
				if (value is TValue && null != value)
				{
					dlg.SelectedObject = (TValue)value;
				}
				else if (typeof(TValue).HasPublicDefaultConstructor())
				{
					dlg.SelectedObject = Activator.CreateInstance<TValue>();
				}
				else
				{
					dlg.SelectedObject = default(TValue);
				}

				if (dlg.ShowDialog() == DialogResult.OK)
				{
					return dlg.SelectedObject;
				}
			}

			return value;
		}

		public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
		{
			return UITypeEditorEditStyle.Modal | UITypeEditorEditStyle.Modal;
		}

	}
}
